开发环境

本章中的工具应该避免在生产环境中使用。

使用map

打包a.js、b.js、c.js文件为bundle.js文件,如果b.js文件有语法错误,错误会指向bundle.js文件,这对于调试很不方便,所以这里可以通过map来定位到错误的地方。

编辑webpack.config.js文件,使用inline-source-map选项:

const path = require('path');
const HtmlWebpackPlugin = require('htmlWebpackPlugin');

module.exports = {
    entry:{
        app:'./src/index.js',
        print:'./src/print.js'
    },
    devtool:'inline-source-map',
    plugins:[
        new HtmlWebpackPlugin({
            title:"输出管理"
        })
    ],
    output:{
        filename:"[name].bundle.js",
        path:path.resolve(__dirname,'dist')   
    }
}

然后故意把print.js写错:

export default function(){
    aler("I come from print.js")
}

命令行运行命令。浏览器打开index.html,点击按钮,可以发现控制台正确定位了错误。

选择一个开发工具

之前所有的例子,每次修改一个文件,都要重新执行命令去编译,这很是一个痛苦的过程,所以这里介绍三种监听文件修改自动编译的工具。

webpack watch mode

首先配置package.json文件,添加scripts:

{
    "scripts":{
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --config webpack.config.js",
        "watch": "webpack --watch"
    }
}

命令行运行npm run watch,启动服务。

这样每次文件修改,都会自动重新编译,只需要刷新浏览器即可。

使用webpack-dev-server

这个要高级一点,首先先安装:

npm install --save-dev webpack-dev-server

配置webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('htmlWebpackPlugin');

module.exports = {
    entry:{
        app:'./src/index.js',
        print:'./src/print.js'
    },
    devtool:'inline-source-map',
    devServer:{
        contentBase:'./dist',//以此目录作为服务器监听的文件,默认端口号是8080
    },
    plugins:[
        new HtmlWebpackPlugin({
            title:"输出管理"
        })
    ],
    output:{
        filename:"[name].bundle.js",
        path:path.resolve(__dirname,'dist')   
    }
}

配置package.json文件:

{
    "scripts":{
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --config webpack.config.js",
        "start": "webpack-dev-server --open"
    }
}

命令行运行:npm run start,会启动一个端口号为8080的本地服务,修改任意文件,会自动编译并刷新浏览器。

使用webpack-dev-middleware

这个官网还没有文档。

results matching ""

    No results matching ""